package com.space.school.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class SpaceJDBCUtils {
//    1.定义成员变量
    private static DataSource ds;
//    静态代码块 修饰里的内容会比构造函数更早实现
//    2.预先加载配置文件
    static {
        Properties ps = new Properties();
        try{
//            使用Properties对象来加载配置文件druid.properties
            ps.load(SpaceJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//            初始化 DataSource
            ds = DruidDataSourceFactory.createDataSource(ps);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    //    DataSource ds数据来源让外部可以取到
    public static DataSource getDs(){
        return ds;
    }
//        获取连接方式
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
//    关闭修改流
    public static void close(Connection connection,Statement statement){
        close(connection,statement,null);
    }
//    关闭查询流
    public static void close(Connection connection, Statement statement,  ResultSet resultSet){
        if (connection != null) {
            try {
                connection.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
